package com.sxjh.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync //开启异步
public class ExecutorConfig {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    @Value("${executor.corePoolSize:50}")
    private int corePoolSize;
    @Value("${executor.maxPoolSize:100}")
    private int maxPoolSize;
    @Value("${executor.queueCapacity:2000}")
    private int queueCapacity;
    @Value("${executor.threadNamePrefix:async-service-}")
    private String threadNamePrefix;
    @Value("${executor.keepAliveSeconds:3000}")
    private int keepAliveSeconds;

    /**
     * Async不能由本类内其他函数调用，必须是外部使用者调用，
     * 如果内部函数调用会出现代理绕过的问题，从而无法执行异步，不会出错，会变成同步操作。
     * 看起来就是@Async失效的状态。
     * @return
     */
    @Bean("taskExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        logger.info("start taskExecutor");
        //ThreadPoolExecutor 这个类是JDK中的线程池类，继承自Executor
        //ThreadPoolTaskExecutor 这个类则是spring包下的，是sring为我们提供的线程池类
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //配置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //配置队列大小
        executor.setQueueCapacity(queueCapacity);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix(threadNamePrefix);
        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }
}
